function initRecent() {
    // 基于准备好的dom，初始化echarts实例
    // var myChart = echarts.init(document.getElementById('recent'));
    // 指定图表的配置项和数据
    var option = {
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['评论增长数']
        },
        grid: {
            left: '3%',
            right: '4%',
            bottom: '3%',
            containLabel: true
        },
        xAxis: {
            type: 'category',
            boundaryGap: false,
            data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '评论增长数',
                type: 'line',
                stack: '总量',
                data: [120, 132, 101, 134, 90, 230, 210]
            }
        ]
    };

    // 使用刚指定的配置项和数据显示图表。
    recent.setOption(option);
}

function queryRecent() {
    var startDate = $("#startDate").val();
    var endDate = $("#endDate").val();
    if (Aid === 0) {
        return;
    }
    recent.showLoading();
    $.post("/ajax/getCommentCount", {startDate: startDate, endDate: endDate, Aid: Aid}, function (json) {
        var data = $.parseJSON(json);
        recent.hideLoading();
        recent.setOption({
            xAxis: {
                type: 'category',
                boundaryGap: false,
                data: data.day
            },
            series: [
                {
                    name: '评论增长数',
                    type: 'line',
                    stack: '总量',
                    data: data.count
                }
            ]
        });
    })
}

function changeEcharts() {
    var datepicker = $(".datepicker");
    recent = echarts.init(document.getElementById('recent-1'));
    initRecent();
    queryRecent();
    datepicker.change(function () {
        $(".recent-date .datepicker-a").removeClass("actived");
        datepicker.eq(0).datepicker("option", "maxDate", $("#endDate").val());
        queryRecent();
    });
}

function datepicker() {
    var datepicker = $(".datepicker");
    var dateinput = $(".recent-date");
    var start = $("#startDate");
    var end = $("#endDate");

    var date;
    var startDate;
    var endDate;

    date = new Date();
    endDate = dateToStr(date);
    startDate = dateToStr(date - 3600 * 1000 * 24 * 7);
    start.val(startDate);
    end.val(endDate);

    datepicker.datepicker({
        changeMonth: true,
        changeYear: true,
        minDate: "-2Y",
        maxDate: 0,
        dateFormat: "yy-mm-dd"
    });

    dateinput.delegate(".datepicker-a", "click", function () {
        switch ($(this).text()) {
            case "最近一周": {
                date = new Date();
                startDate = dateToStr(date - 3600 * 1000 * 24 * 7);
                endDate = dateToStr(date);
                start.val(startDate);
                end.val(endDate);
                start.change();
                break;
            }
            case "最近一个月": {
                date = new Date();
                endDate = dateToStr(date);
                date.setMonth(date.getMonth() - 1);
                startDate = dateToStr(date);
                start.val(startDate);
                end.val(endDate);
                start.change();
                break;
            }
            case "最近三个月": {
                date = new Date();
                endDate = dateToStr(date);
                date.setMonth(date.getMonth() - 3);
                startDate = dateToStr(date);
                start.val(startDate);
                end.val(endDate);
                start.change();
                break;
            }
            case "最近一年": {
                date = new Date();
                endDate = dateToStr(date);
                date.setMonth(date.getMonth() - 12);
                startDate = dateToStr(date);
                start.val(startDate);
                end.val(endDate);
                start.change();
                break;
            }
        }
        $(this).addClass("actived");
    });
}

function initLike() {
    // var myChart = echarts.init(document.getElementById('like'));
    // 指定图表的配置项和数据
    var option = {
        tooltip: {
            trigger: 'item',
            formatter: "{a} <br/>{b}: {c} ({d}%)"
        },
        legend: {
            orient: 'vertical',
            x: 'left',
            data: ['一星', '二星', '三星', '四星', '五星']
        },
        series: [
            {
                name: '喜好程度',
                type: 'pie',
                radius: ['50%', '70%'],
                avoidLabelOverlap: false,
                label: {
                    normal: {
                        show: false,
                        position: 'center'
                    },
                    emphasis: {
                        show: true,
                        textStyle: {
                            fontSize: '30',
                            fontWeight: 'bold'
                        }
                    }
                },
                labelLine: {
                    normal: {
                        show: false
                    }
                },
                data: [
                    {value: 335, name: '一星'},
                    {value: 310, name: '二星'},
                    {value: 234, name: '三星'},
                    {value: 135, name: '四星'},
                    {value: 1548, name: '五星'}
                ]
            }
        ]
    };
    // 使用刚指定的配置项和数据显示图表。
    like.setOption(option);
}

function queryLike(startDate, endDate) {
    if (Aid === 0) {
        return;
    }
    like.showLoading();
    $.post("/ajax/getRankCount", {startDate: startDate, endDate: endDate, Aid: Aid}, function (json) {
        var data = $.parseJSON(json);
        like.hideLoading();
        like.setOption({
            tooltip: {
                trigger: 'item',
                formatter: "{a} <br/>{b}: {c} ({d}%)"
            },
            legend: {
                orient: 'vertical',
                x: 'left',
                data: ['一星', '二星', '三星', '四星', '五星']
            },
            series: [
                {
                    data: data
                }
            ]
        });
    });
}

function like() {
    like = echarts.init(document.getElementById('like-1'));
    var date = new Date();
    var startDate = dateToStr(date - 3600 * 1000 * 24 * 7);
    var endDate = dateToStr(date);
    initLike();
    queryLike(startDate, endDate);

    $(".follow-like-date").delegate("a", "click", function () {
        $(".follow-like-date").children().removeClass("actived");
        $(this).addClass("actived");
        switch ($(this).text()) {
            case "最近一周": {
                date = new Date();
                startDate = dateToStr(date - 3600 * 1000 * 24 * 7);
                endDate = dateToStr(date);
                break;
            }
            case "最近一个月": {
                date = new Date();
                endDate = dateToStr(date);
                date.setMonth(date.getMonth() - 1);
                startDate = dateToStr(date);
                break;
            }
            case "最近三个月": {
                date = new Date();
                endDate = dateToStr(date);
                date.setMonth(date.getMonth() - 3);
                startDate = dateToStr(date);
                break;
            }
            case "最近一年": {
                date = new Date();
                endDate = dateToStr(date);
                date.setMonth(date.getMonth() - 12);
                startDate = dateToStr(date);
                break;
            }
        }
        queryLike(startDate, endDate);
    });
}

function initFollow() {
    Aid = $("#username").data("spaid");
    var username = $("#username").data("username");
    var date = new Date();
    var startDate = dateToStr(date - 3600 * 1000 * 24 * 7);
    var endDate = dateToStr(date);
    var appName = $("#follow-app-name");

    followList = $(".follow-group");
    followList.delegate(".btn-a-primary", "click", function () {
        Aid = $(this).data("aid");
        var a = $(".follow-group .btn-a-primary");
        a.removeClass("actived");
        a.text("选择");
        $(this).addClass("actived");
        $(this).text("已选择");
        queryRecent();
        queryLike(startDate, endDate);
        queryCloud(startDate, endDate);
        queryContrast();
        appName.text($(this).prev().text());
    });
    queryFollow();
}

function queryFollow() {
    var username = $("#username").data("username");

    $.post("/ajax/getFollow", {username: username}, function (json) {
        var res = $.parseJSON(json);
        var total = res.total;
        var follows = res.follows;
        var followApp;
        var appName = $("#follow-app-name");

        followList = $(".follow-group");
        followList.html("");
        for (i = 0; i < total; i++) {
            followApp = $('<div class="follow-app">' +
                ' <img class="app-logo" src="/logo?file=' + follows[i].logo + '">' +
                ' <span class="follow-app-name">' + follows[i].name + '</span><a class="btn-a-primary" data-aid="' + follows[i].AID + '">选择</a>' +
                ' </div>');
            if (Aid === follows[i].AID) {
                var a = followApp.children().eq(2);
                a.text("已选择");
                a.addClass("actived");
                appName.text(follows[i].name);
            }
            followList.append(followApp);
        }

    });
}
function cloud() {
    var date = new Date();
    var startDate = dateToStr(date - 3600 * 1000 * 24 * 7);
    var endDate = dateToStr(date);
    queryCloud(startDate, endDate);

    $(".follow-cloud-date").delegate("a", "click", function () {
        $(".follow-cloud-date").children().removeClass("actived");
        $(this).addClass("actived");
        switch ($(this).text()) {
            case "最近一周": {
                date = new Date();
                startDate = dateToStr(date - 3600 * 1000 * 24 * 7);
                endDate = dateToStr(date);
                break;
            }
            case "最近一个月": {
                date = new Date();
                endDate = dateToStr(date);
                date.setMonth(date.getMonth() - 1);
                startDate = dateToStr(date);
                break;
            }
            case "最近三个月": {
                date = new Date();
                endDate = dateToStr(date);
                date.setMonth(date.getMonth() - 3);
                startDate = dateToStr(date);
                break;
            }
            case "最近一年": {
                date = new Date();
                endDate = dateToStr(date);
                date.setMonth(date.getMonth() - 12);
                startDate = dateToStr(date);
                break;
            }
        }
        queryCloud(startDate, endDate);
    });
}
function queryCloud(startDate, endDate) {
    $.post("/ajax/getHotWords", {
        Aid: Aid,
        startDate: startDate,
        endDate: endDate
    }, function (json) {
        var res = $.parseJSON(json);
        var data = res.hot.data;
        var total = res.hot.total;
        var i;
        var obj;
        var array = new Array();
        for (i = 0; i < total; i++) {
            obj = new Object();
            obj.text = data.text[i];
            obj.weight = data.weight[i];
            array.push(obj);
        }
        // var word_array = [
        //     {text: "Lorem", weight: 15},
        //     {text: "Ipsum", weight: 9, link: "http://jquery.com/"},
        //     {text: "Dolor", weight: 6, html: {title: "I can haz any html attribute"}},
        //     {text: "Sit", weight: 7},
        //     {text: "Amet", weight: 5}
        // ];
        cloud = $("#cloud");
        cloud.html("");
        cloud.jQCloud(array, {
            removeOverflowing: true,
            shape: "elliptic",
            width: 400,
            height: 400
        });
    });
}

function initContrast() {
    Contrast = echarts.init(document.getElementById('contrast'));
    var option = {
        tooltip: {},
        legend: {
            data: ['应用评分', '同类评分']
        },
        radar: {
            // shape: 'circle',
            indicator: [
                {name: '一星', max: 100},
                {name: '两星', max: 100},
                {name: '三星', max: 100},
                {name: '四星', max: 100},
                {name: '五星', max: 100}
            ]
        },
        series: [{
            type: 'radar',
            // areaStyle: {normal: {}},
            data: [
                {
                    value: [0, 20, 0, 0, 80],
                    name: '应用评分'
                },
                {
                    value: [10, 20, 30, 40, 50],
                    name: '同类评分'
                }
            ]
        }]
    };

    // 使用刚指定的配置项和数据显示图表。
    Contrast.setOption(option);
    queryContrast();
}
function queryContrast() {
    Contrast.showLoading();
    $.post("/ajax/getGroupCount", function (jsonG) {
        $.post("/ajax/getRankCount", {Aid: Aid}, function (jsonA) {
            Contrast.hideLoading();
            var dataGroup = $.parseJSON(jsonG);
            var dataApp = $.parseJSON(jsonA);
            var totalGroup = 0;
            var totalApp = 0;
            var arrGroup = Array();
            var arrApp = Array();
            var max = 0;

            dataApp.forEach(function (v, index, ar) {
                if (v.value === null) {
                    return;
                }
                totalApp += parseInt(v.value);
            });
            dataApp.forEach(function (v, index, ar) {
                if (v.value === null) {
                    return;
                }
                if(max <parseInt(parseInt(v.value) / totalApp * 100) ){
                    max = parseInt(parseInt(v.value) / totalApp * 100);
                }
                arrApp.push(parseInt(parseInt(v.value) / totalApp * 100));
            });
            dataGroup.forEach(function (v, index, ar) {
                if (v.value === null) {
                    return;
                }
                totalGroup += parseInt(v.value);

            });
            dataGroup.forEach(function (v, index, ar) {
                if (v.value === null) {
                    return;
                }
                if(max <parseInt(parseInt(v.value) / totalApp * 100) ){
                    max = parseInt(parseInt(v.value) / totalApp * 100);
                }
                arrGroup.push(parseInt(parseInt(v.value) / totalGroup * 100));
            });
            var option = {
                legend: {
                    data: ['应用评分', '同类评分']
                },
                radar: {
                    // shape: 'circle',
                    indicator: [
                        {name: '一星', max: (arrApp[0] > arrGroup[0]) ? arrApp[0]+5 :arrGroup[0]+5},
                        {name: '两星', max: (arrApp[1] > arrGroup[1]) ? arrApp[1]+5 :arrGroup[1]+5},
                        {name: '三星', max: (arrApp[2] > arrGroup[2]) ? arrApp[2]+5 :arrGroup[2]+5},
                        {name: '四星', max: (arrApp[3] > arrGroup[3]) ? arrApp[3]+5 :arrGroup[3]+5},
                        {name: '五星', max: (arrApp[4] > arrGroup[4]) ? arrApp[4]+5 :arrGroup[4]+5}
                    ]
                },
                series: [{
                    type: 'radar',
                    data: [
                        {
                            value: arrApp,
                            name: '应用评分'
                        },
                        {
                            value: arrGroup,
                            name: '同类评分'
                        }
                    ]
                }]
            };
            Contrast.setOption(option);
            console.log(dataApp);
            console.log(dataGroup);
        })
    })
}

$(function () {
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    initFollow();
    datepicker();
    changeEcharts();
    like();
    initContrast();
    cloud();
});
